package com.zhiwei.jenkins.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class PasswordUtil {
    private static final Logger logger = LoggerFactory.getLogger(PasswordUtil.class);

    /**
     * 将passowrd + salt 进行MD5加密
     * @param str
     * @return
     */
    public static String md5(String str) {
        try {
            // MessageDigest是封装md5算法的工具对象还支持SHA算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 通过digest拿到的任意字符串,得到的bytes都是等长的
            byte[] bytes = md.digest(str.getBytes("utf-8"));
            // 把二进制转换成十六进制
            return toHex(bytes);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 把toHex的字符串把二进制转换成十六进制
     * @param bytes
     * @return
     */
    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        // 循环判断是为了补位操作
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    /**
     * 随机生成salt
     * @return
     */
    public static String salt() {
        String uuid = UUIDUtil.getUUID();
        String[] arr = uuid.split("-");
        return arr[0];
    }
}
